import pymysql
from pymysql.converters import escape_string
import json



class Mysql:
    # 初始化
    def __init__(self):
        # 链接数据库
        try:
            connt = pymysql.connect(
                host="127.0.0.1",
                port=3306,
                user="root",
                password="yhy258012",
                database="myshop",
                charset="utf8"

            )
            self.cont = connt
            self.curson = connt.cursor(cursor=pymysql.cursors.DictCursor)
            print("链接成功")
        except Exception as err:
            print("链接失败", err)

    # 添加数据
    def insert_updata_delete(self, sql):
        try:
            self.curson.execute(sql)
            self.cont.commit()
            print('操作成功')
            return 1
        except Exception as err:
            print("操作失败", err)
            return 0

    # 查询数据
    def select_db(self, sql, number):
        try:
            self.curson.execute(sql)
            if number:
                return self.curson.fetchall()
            else:
                return self.curson.fetchone()
        except Exception as err:
            print("查询失败", err)

    # 关闭链接
    def close(self):
        self.curson.close()
        self.cont.close()



